package org.libraq.hrm.zuulfilter;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class ZuulFilter extends com.netflix.zuul.ZuulFilter {

    /**
     * 选择过滤器类型 （pre routing post error）
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     *  选择优先级 数字越小 优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 执行Run方法之前的逻辑 前置过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //利用请求对象 获取uri（url？）
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();//字符串比较器
        if(antPathMatcher.match("/services/user/user/login",requestURI)||antPathMatcher.match("/register",requestURI))
            return false; // 若为登录、注册请求 则直接放行
        return true; // true: 走run方法
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            try {
                response.setContentType("application/json;charset=utf-8");// 设置字符编码 及返回格式 ！
                response.getWriter().write("{\"success\":false,\"message\":\"请先完成登录！\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null; //null：通关， 前往下一拦截关卡
    }
}
